package com.backend.modules.task.entity;

import com.backend.common.entity.BaseEntity;
import com.backend.modules.system.entity.SysDepartment;
import com.backend.modules.system.entity.SysUser;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 任务实体
 * 教师创建的作业任务
 */
@Data
@Entity
@Table(name = "task")
@ToString(exclude = {"teacher", "classInfo", "submissions"})
@EqualsAndHashCode(callSuper = true)
@SQLDelete(sql = "UPDATE task SET deleted = true WHERE id = ?")
@Where(clause = "deleted = false")
public class Task extends BaseEntity {
    
    /**
     * 任务名称
     */
    @Column(nullable = false)
    private String name;
    
    /**
     * 任务描述
     */
    @Column(columnDefinition = "text")
    private String description;
    
    /**
     * 截止时间
     */
    @Column(nullable = false)
    private LocalDateTime deadline;
    
    /**
     * 文件要求
     */
    @Column(columnDefinition = "text")
    private String fileRequirements;
    
    /**
     * 提交要求
     */
    @Column(columnDefinition = "text")
    private String submitRequirements;
    
    /**
     * 关联的班级
     * 一对一关系，一个任务只能分配给一个班级
     */
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "class_id")
    private SysDepartment classInfo;

    @Column(name = "class_id", insertable = false, updatable = false)
    private Long classId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teacher_id")
    private SysUser teacher;

    @Column(name = "teacher_id", insertable = false, updatable = false)
    private Long teacherId;

    @OneToMany(mappedBy = "task", cascade = CascadeType.ALL, orphanRemoval = true)
    @OrderBy("submitTime DESC")
    private List<TaskSubmission> submissions = new ArrayList<>();

    /**
     * 添加提交记录
     */
    public void addSubmission(TaskSubmission submission) {
        submissions.add(submission);
        submission.setTask(this);
    }

    /**
     * 移除提交记录
     */
    public void removeSubmission(TaskSubmission submission) {
        submissions.remove(submission);
        submission.setTask(null);
    }

    /**
     * 设置任务所属班级
     */
    public void setClassInfo(SysDepartment department) {
        this.classInfo = department;
        this.classId = department != null ? department.getId() : null;
    }
} 